package com.springBoot.springBootSysCore.modules.services.system.impl;

import com.springBoot.springBootSysCore.common.service.IBaseServiceImpl;
import com.springBoot.springBootSysCore.common.utils.CacheUtils;
import com.springBoot.springBootSysCore.common.utils.IdGen;
import com.springBoot.springBootSysCore.common.utils.returnUtil.CodeEnum;
import com.springBoot.springBootSysCore.common.utils.returnUtil.ResultJsonFormat;
import com.springBoot.springBootSysCore.modules.entity.system.SysDict;
import com.springBoot.springBootSysCore.modules.entity.system.SysResource;
import com.springBoot.springBootSysCore.modules.entity.system.SysRole;
import com.springBoot.springBootSysCore.modules.entity.system.SysUser;
import com.springBoot.springBootSysCore.modules.entity.utils.DictUtils;
import com.springBoot.springBootSysCore.modules.entity.utils.UserUtils;
import com.springBoot.springBootSysCore.modules.enums.base.DeleteStateEnum;
import com.springBoot.springBootSysCore.modules.repository.system.SysResourceRepository;
import com.springBoot.springBootSysCore.modules.repository.system.SysRoleRepository;
import com.springBoot.springBootSysCore.modules.repository.system.SysUserRepository;
import com.springBoot.springBootSysCore.modules.services.system.SysRoleService;
import com.springBoot.springBootSysCore.modules.vo.TreeNodeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * 角色Service实现
 * @author PSC
 * 2015年11月27日
 */
@Service
public class SysRoleServiceImpl extends IBaseServiceImpl<SysRole, String> implements SysRoleService {
	@Autowired
	private SysRoleRepository sysRoleRepository;
	@Autowired
	private SysResourceRepository sysResourceRepository;

	@Override
	@Transactional
	public Map<String, Object> saveEntity(SysRole sysRole, String resIds) {
		ResultJsonFormat rj = new  ResultJsonFormat("保存成功", CodeEnum.SUCCESS.value());
		try {
			List<String> ids = sysRoleRepository.queryIdByName(sysRole.getName());
			Map<String, Object>  map = crosschecking(ids, sysRole.getId(), rj,"角色名不允许重复");
			if(map!=null){
				return map;
			}

			if(StringUtils.isNotBlank(resIds)){
				List<String> resourceIds = Arrays.asList(resIds.split(","));
				List<SysResource> resources = sysResourceRepository.findByIds(resourceIds);
				sysRole.setResources(resources);
			}else{
				sysRole.setResources(null);
			}

			boolean isUpdate =false;

			if(StringUtils.isBlank(sysRole.getId())){
				if(StringUtils.isBlank(sysRole.getCode())){
					sysRole.setCode(IdGen.get36UUID());//默认
				}
				sysRole.preInsert();
				sysRoleRepository.save(sysRole);
			}else{
				isUpdate=true;
				SysRole dbRole = sysRoleRepository.findOne(sysRole.getId());
				dbRole.EntityCopy(dbRole,sysRole);
				dbRole.setResources(sysRole.getResources());
//				ca
				UserUtils.clearCache();
			}
		} catch (Exception e) {
			rj.setMsg("系统错误");
			rj.setFlag(CodeEnum.ERROR.value());
			e.printStackTrace();
		}
		return rj.convertResultJson();
	}

	@Override
	@Transactional
	public Map<String, Object> deleteEntity(List<String> asList) {
		ResultJsonFormat ret = new ResultJsonFormat("删除成功", CodeEnum.SUCCESS.value());
		try {
			sysRoleRepository.deleteRolesById(asList);
		} catch (Exception e) {
			e.printStackTrace();
			ret.setMsg("角色存在关联,删除失败!");
			ret.setFlag(CodeEnum.ERROR.value());
		}
		return ret.convertResultJson();
	}

	@Override
	@Transactional
	public Map<String, Object> deleteEntity(SysRole entity) {
		ResultJsonFormat rj = new  ResultJsonFormat("删除成功", CodeEnum.SUCCESS.value());
		try {
			if(StringUtils.isNoneBlank(entity.getId())){
				if(entity.isSureDel()){
					sysRoleRepository.delete(entity.getId());
				}else{
//					sysUserRepository.updateEntityById(user);
				}
			}else{
				String ids = "";
				String[] a = entity.getIds().split(",");
				for(int i = 0 ; i < a.length ;i++ ){
					ids += "'"+a[i]+"'";
					if(i!=a.length-1){
						ids +=",";
					}
				}
				if(entity.isSureDel()){
					sysRoleRepository.deleteRolesById(Arrays.asList(a));
				}else{
//					sysRoleRepository.updateDelFlag(Arrays.asList(a));
				}
			}
			//如果数据被使用设置为CodeEnum.Failed
			CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return rj.convertResultJson();
	}

	@Override
	public List<TreeNodeVo> findAllOfNotDefal(String userId) {
		List<String> userRoleLi = sysRoleRepository.findRoleIdByUser(userId);
		List<SysRole> allRoleLi =  sysRoleRepository.findAll(new Sort(Direction.DESC, "createDate"));
		List<TreeNodeVo> treeNodeLi = new ArrayList<TreeNodeVo>();
		for(SysRole role : allRoleLi){
			if(role.getIsSysRole()){
				continue;
			}
			TreeNodeVo vo = new TreeNodeVo();
			vo.setId(role.getId());
			vo.setName(role.getName());
			vo.setText(role.getName());
			if(userRoleLi.contains(role.getId())){
				vo.setChecked(true);
			}
			treeNodeLi.add(vo);
		}
		return treeNodeLi;
	}

	@Override
	public List<SysRole> findAllPublic() {
		return sysRoleRepository.findAll(new Specification<SysRole>() {
			@Override
			public Predicate toPredicate(Root<SysRole> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list=new ArrayList<Predicate>();
				list.add(criteriaBuilder.isFalse(root.get("isSysRole").as(Boolean.class)));
				list.add(criteriaBuilder.equal(root.get("delFlag").as(String.class), DeleteStateEnum.NO_DELETE.getVal()));
				criteriaQuery.where(list.toArray(new Predicate[list.size()]));
				return criteriaQuery.getRestriction();
			}
		});
	}

}
